package com.example.administrator.hqq.base;


import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;

import com.aliyun.sls.android.sdk.ClientConfiguration;
import com.aliyun.sls.android.sdk.LOGClient;
import com.aliyun.sls.android.sdk.LogException;
import com.aliyun.sls.android.sdk.SLSDatabaseManager;
import com.aliyun.sls.android.sdk.SLSLog;
import com.aliyun.sls.android.sdk.core.auth.PlainTextAKSKCredentialProvider;
import com.aliyun.sls.android.sdk.core.callback.CompletedCallback;
import com.aliyun.sls.android.sdk.model.LogGroup;
import com.aliyun.sls.android.sdk.request.PostLogRequest;
import com.aliyun.sls.android.sdk.result.PostLogResult;
import com.aliyun.sls.android.sdk.utils.IPService;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.SPUtils;

import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.UmengNotificationBean;
import com.example.administrator.hqq.bean.event.InformationEvent;
import com.example.administrator.hqq.bean.group.RongIMGroupBean;
import com.example.administrator.hqq.bean.group.UserInfoBean;
import com.example.administrator.hqq.config.ENV;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;

import com.example.administrator.hqq.service.AppMqttService;
import com.example.administrator.hqq.utils.MqttUtils;
import com.example.administrator.hqq.utils.RongIMUtils;

import com.example.administrator.hqq.utils.VoiceAndVIbratorUtils;
import com.google.gson.Gson;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import com.umeng.message.UmengMessageHandler;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.entity.UMessage;
import com.umeng.message.tag.TagManager;
import com.zhy.autolayout.config.AutoLayoutConifg;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;


import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;

import io.rong.message.ImageMessage;
import io.rong.message.TextMessage;
import io.rong.push.notification.PushNotificationMessage;
import okhttp3.Call;
import okhttp3.OkHttpClient;

/**
 * @name: HQQ
 * @describe: 程序入口
 * @author: 康海涛 QQ2541849981
 * @time: 2018/10/29 10:13
 * @remark:
 */
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {

    private Context context=this;
    private int count = 0;
    private String TAG=this.getClass().getSimpleName();
    private static PushAgent mPushAgent;
    private Handler handler = new Handler() {
        // 处理子线程给我们发送的消息。
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case IPService.HANDLER_MESSAGE_GETIP_CODE:
                    source_ip = (String) msg.obj;
                    Log.e(TAG, "source_ip: "+source_ip );
                    return;
            }
            super.handleMessage(msg);
        }
    };
    private static boolean isFront=true;
    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        AutoLayoutConifg.getInstance().useDeviceSize();
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        //配置okhttp可以进行https请求
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor("HQQ"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(okHttpClient);
        //初始化腾讯buglyget
        CrashReport.initCrashReport(getApplicationContext(), "4d89ca4082", false);
        if (isAppProcess()) {
            //初始化融云IM
            RongIM.init(this);
            RongIM.setOnReceiveMessageListener(new MyReceiveMessageListener());
            setRongIMInfo();
        }
        //初始化友盟
        initUM();
        registerActivityLifecycleCallbacks(this);
        //初始化阿里Log日志上传
        initAliLog();
    }
    /**
     * 阿里Log上传填入必要的参数
     */
    public String endpoint = "http://cn-beijing.log.aliyuncs.com";
    public static String project = "hqq-log-service";
    public static String logStore = "android-normal-log-1";
    public static String source_ip = "";
    //client的生命周期和app保持一致
    public static LOGClient logClient;

    /**
     * 初始化阿里的LOg上传Ciient
     */
    private void initAliLog() {
        SLSDatabaseManager.getInstance().setupDB(getApplicationContext());
        try {
            IPService.getInstance().asyncGetIp(IPService.DEFAULT_URL, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //        主账户使用方式
        String AK = "LTAIfKcprOS1g3F6";
        String SK = "sk4aPXB03oVddXQ1lV0V22wgQS3lho";
        PlainTextAKSKCredentialProvider credentialProvider = new PlainTextAKSKCredentialProvider(AK, SK);
        // 配置信息
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        conf.setCachable(true);     // 设置日志发送失败时，是否支持本地缓存。
        conf.setConnectType(ClientConfiguration.NetworkPolicy.WIFI_ONLY);   // 设置缓存日志发送的网络策略。
        SLSLog.enableLog(); // log打印在控制台
        logClient = new LOGClient(getApplicationContext(), endpoint, credentialProvider, conf);    // 初始化client
    }

    /*
     *  推荐使用的方式，直接调用异步接口，通过callback 获取回调信息
     */
    public static void asyncUploadLog(String topic,String s) {
        /* 创建logGroup */
        LogGroup logGroup = new LogGroup(topic, TextUtils.isEmpty(DeviceUtils.getMacAddress()) ? "none" : DeviceUtils.getMacAddress());
        /* 存入一条log */
        com.aliyun.sls.android.sdk.model.Log log= new com.aliyun.sls.android.sdk.model.Log();
        log.PutContent("current time ", "" + System.currentTimeMillis() / 1000);
        log.PutContent("content", s);
        logGroup.PutLog(log);
        try {
            PostLogRequest request = new PostLogRequest(project, logStore, logGroup);
            logClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
                @Override
                public void onSuccess(PostLogRequest request, PostLogResult result) {
                    Log.e("ali", "onSuccess: " );
                }

                @Override
                public void onFailure(PostLogRequest request, LogException exception) {
                    Log.e("ali", "onFailure: "+exception.getMessage());
                }
            });
        } catch (LogException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化友盟SDK
     */
    private void initUM() {
        //初始化友盟
        //设置友盟组件化的Log开关
        UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE, "8a66c7f041fdc1d61270bef3ce2be7f0");
        UMConfigure.setLogEnabled(true);
        MobclickAgent.setSecret(this, "0mkskia2fscpqwu9jj5bo2gt4bvgg1y9");
        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_UM_NORMAL);
        //获取消息推送代理示例
        mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.e("MobclickAgent", "注册成功：deviceToken：-------->  " + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("MobclickAgent", "注册失败：-------->  " + "s:" + s + "s1:" + s1);
            }
        });
        //友盟推送自定义消息类监听
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                Log.e(TAG, "dealWithCustomMessage: " + msg.custom);
                disposeUmengMessage(msg.custom);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);
        //设置标签
        setUmTags(ENV.getUmTag());

    }

    /**
     * 处理Umeng下发的消息
     * @param custom
     */
    private void disposeUmengMessage(String custom) {

    }

    /**
     * 为友盟的推送设置别名
     * @param UserId 用户id
     */
    public static void setUMAlias(String UserId){
        mPushAgent.setAlias(UserId, "HQQ", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                Log.e("MobclickAgent", "onMessage: "+s);
            }
        });
    }

    public static void deleteAlias(String UserID){
        //移除别名ID
        mPushAgent.deleteAlias(UserID, "HQQ", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
                Log.e("MobclickAgent", "onMessage: "+message);
            }
        });
    }
    /**
     * 断开友盟的推送
     */
    public static void disable(){
        mPushAgent.disable(new IUmengCallback() {
            @Override
            public void onSuccess() {
                Log.e("kang", "onSuccess: " );
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("kang", "onFailure: " );
            }
        });
    }

    /**
     * 设置会话接面和会话列表界面的展示信息
     */
    private void setRongIMInfo() {
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String userId) {
                Log.e(TAG, "getUserInfo: " + userId);
                return findUserById(userId);//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
            }
        }, true);
        RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {
            @Override
            public Group getGroupInfo(final String s) {
                OkHttpUtils.get().url(UrlFactory.getGroupInfo())
                        .addParams(LoongsConfig.group_id,s)
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "onError: ");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "onResponse: " );
                        Gson gson = new Gson();
                        RongIMGroupBean rongIMGroupBean = gson.fromJson(response, RongIMGroupBean.class);
                        if (rongIMGroupBean.getCode()==200)
                            RongIM.getInstance().refreshGroupInfoCache(new Group(s,rongIMGroupBean.getList_title(), Uri.parse(rongIMGroupBean.getUrl())));
                    }
                });
                return null;
            }
        },false);
    }

    /**
     * 为融云体贴UserInfo来展示聊天页面的用户信息
     * @param userId 传入用户id
     * @return UserInfo
     */
    private UserInfo findUserById(final String userId) {
        Log.e(TAG, "userId: " + userId);
        OkHttpUtils.get().url(UrlFactory.getUserInfo())
                .addParams(LoongsConfig.user_id, userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "onError: " + e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "onResponse: " + response);
                        Gson gson = new Gson();
                        UserInfoBean userInfoBean = gson.fromJson(response, UserInfoBean.class);
                        if (userInfoBean.getCode() == 200) {
                            RongIM.getInstance().refreshUserInfoCache(new UserInfo(userId, userInfoBean.getNickname(), Uri.parse(userInfoBean.getUrl())));
                        }
                    }
                });
        return null;
    }
    /**
     *监听页面切换到后台
     */
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (count == 0) {
            if (!isTopActivity("com.example.administrator.hqq.activity.register.LoadingFigureActivity")&&!isTopActivity("com.example.administrator.hqq.activity.LogInActivity"))
            {
                //开始融云建立消息链接
//                RongIMUtils.connect(SPUtils.getInstance().getString(LoongsConfig.rongToken),this);
            }
        }
        count++;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        count--;
        if (count==0)
        {
            //断开友盟的消息链接走推送通道
//            RongIM.getInstance().disconnect();
            isFront=false;
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    public void setUmTags(String umTags) {
        mPushAgent.getTagManager().addTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {

            }
        },umTags);
    }

    /**
     * 判读APP处于前台还是处于后台
     * @return
     */
    public static boolean isFront() {
        return isFront;
    }

    /**
     * 融云删除本地对话列表
     * @param type
     * @param id
     */
    public static void  removeRongyunConversation(Conversation.ConversationType type,String id){
        //删除本地消息缓存
        RongIM.getInstance().clearMessages(type, id, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
        //删除本地对话框
        RongIM.getInstance().removeConversation(type
                , id,new RongIMClient.ResultCallback<Boolean>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        Log.e("removeRongyunConversation", "onSuccess: "+aBoolean );
                    }

                    @SuppressLint("LongLogTag")
                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        Log.e("removeRongyunConversation", "onError: "+errorCode );

                    }
                });
    }

    /**
     * 融云的消息监听器
     */
    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
        /**
         * 收到消息的处理。
         *
         * @param message 收到的消息实体。
         * @param left    剩余未拉取消息数目。
         * @return 收到消息是否处理完成，true 表示自己处理铃声和后台通知，false 走融云默认处理方式。
         */
        @Override
        public boolean onReceived(final Message message, int left) {

            Log.e("kang", "onReceived: "+message.getTargetId() );
            RongIM.getInstance().getTotalUnreadCount();
            //判断是否开启禁止对话类型的通知
            Log.e("kang", "onReceived: "+LoongsConfig.getUsersIdSPUtils().getBoolean(message.getTargetId(),true));
            if (LoongsConfig.getUsersIdSPUtils().getBoolean(LoongsConfig.MessageNotification.dialogueNotification,true))
            {
                if (!isFront)
                showNotification(getContext(),message);
                //通过融云来获取消息提醒状态
                RongIM.getInstance().getConversationNotificationStatus(message.getConversationType(), message.getTargetId(), new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                    @Override
                    public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                        Log.e("kang", "onSuccess: "+conversationNotificationStatus.getValue() );
                        //value==1时表示未开启消息免打扰
                        if (conversationNotificationStatus.getValue()==1){
                            //同过本地缓存的状态来判断是否开启消息免
                            if (LoongsConfig.getUsersIdSPUtils().getBoolean(message.getTargetId(),true))
                            {
                                try {
                                    VoiceAndVIbratorUtils.playVoice(context);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
                //判断某一个group对话是否开启消息免打扰

            }
            //开发者根据自己需求自行处理
            return true;
        }
    }

    /**
     * @author: 康海涛 QQ2541849981
     * @return context 全局唯一的上下文
     */
    public Context getContext() {
        return context;
    }

    @Override
    public void attachBaseContext(Context base) {
        MultiDex.install(base);
        super.attachBaseContext(base);
    }

    /**'
     * 生成友盟需要的测试设备码
     * @param context 上下文
     * @return 测试设备码
     */
    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = getMac(context);
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMac(Context context) {
        String mac = "";
        if (context == null) {
            return mac;
        }
        if (Build.VERSION.SDK_INT < 23) {
            mac = getMacBySystemInterface(context);
        } else {
            mac = getMacByJavaAPI();
            if (TextUtils.isEmpty(mac)){
                mac = getMacBySystemInterface(context);
            }
        }
        return mac;

    }

    @TargetApi(9)
    private static String getMacByJavaAPI() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface netInterface = interfaces.nextElement();
                if ("wlan0".equals(netInterface.getName()) || "eth0".equals(netInterface.getName())) {
                    byte[] addr = netInterface.getHardwareAddress();
                    if (addr == null || addr.length == 0) {
                        return null;
                    }
                    StringBuilder buf = new StringBuilder();
                    for (byte b : addr) {
                        buf.append(String.format("%02X:", b));
                    }
                    if (buf.length() > 0) {
                        buf.deleteCharAt(buf.length() - 1);
                    }
                    return buf.toString().toLowerCase(Locale.getDefault());
                }
            }
        } catch (Throwable e) {
        }
        return null;
    }

    private static String getMacBySystemInterface(Context context) {
        if (context == null) {
            return "";
        }
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (checkPermission(context, Manifest.permission.ACCESS_WIFI_STATE)) {
                WifiInfo info = wifi.getConnectionInfo();
                return info.getMacAddress();
            } else {
                return "";
            }
        } catch (Throwable e) {
            return "";
        }
    }

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (context == null) {
            return result;
        }
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Throwable e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe (threadMode = ThreadMode.MAIN)
    public void Event(String s){

    }

    private boolean isTopActivity(String packageName) {

        System.out.println("**********************top packageName:"
                + packageName);

        ActivityManager activityManager = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);

        if (tasksInfo.size() > 0) {
            Log.e(TAG, "isTopActivity: "+tasksInfo.get(0).topActivity.getClassName() );
        // 应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity.getClassName())) {
                return true;
            }

        }
        return false;
    }

    /**
     * 判断该进程是否是app进程
     * @return
     */
    public boolean isAppProcess() {
        String processName = getProcessName();
        if (processName == null || !processName.equalsIgnoreCase(this.getPackageName())) {
            return false;
        }else {
            return true;
        }
    }

    /**
     * 获取运行该方法的进程的进程名
     * @return 进程名称
     */
    public String getProcessName() {
        int processId = android.os.Process.myPid();
        String processName = null;
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        Iterator iterator = manager.getRunningAppProcesses().iterator();
        while (iterator.hasNext()) {
            ActivityManager.RunningAppProcessInfo processInfo = (ActivityManager.RunningAppProcessInfo) (iterator.next());
            try {
                if (processInfo.pid == processId) {
                    processName = processInfo.processName;
                    return processName;
                }
            } catch (Exception e) {
//                LogD(e.getMessage())
            }
        }
        return processName;
    }

    /**
     * rongyu消息通知
     * @param context
     * @param pushNotificationMessage
     */
    private void showNotification(Context context, Message pushNotificationMessage) {
        String title="";
        String text="";
        MessageContent messageContent = pushNotificationMessage.getContent();
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            //上传文本消息
            text=textMessage.getContent();
            Log.e(TAG, "文本消息onSent-TextMessage:" + textMessage.getContent());
        } else if (messageContent instanceof ImageMessage) {//图片消息
            ImageMessage imageMessage = (ImageMessage) messageContent;
            //上传图片消息
            text="[图片]";
            Log.e(TAG, "图片消息onSent-ImageMessage:" + imageMessage.getRemoteUri().toString());
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri.Builder builder = Uri.parse("rong://" + context.getPackageName()).buildUpon();
        builder.appendPath("conversation").appendPath(pushNotificationMessage
                .getConversationType().getName())
                .appendQueryParameter("targetId", pushNotificationMessage.getTargetId())
                .appendQueryParameter("title","您有一条新消息");
        Uri uri = builder.build();
        intent.setData(uri);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        NotificationManager manger = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(context);
        builder1.setContentTitle("您有一条新消息");//设置标题，必要
        builder1.setContentText(text);//设置内容，必要
        builder1.setWhen(System.currentTimeMillis());//设置时间，默认设置，可以忽略
        builder1.setSmallIcon(R.mipmap.logo);//设置通知栏的小图标，必须设置
        builder1.setAutoCancel(true);//设置自动删除，点击通知栏信息之后系统会自动将状态栏的通知删除，要与setContentIntent连用
        builder1.setContentIntent(pendingIntent);
        builder1.setTicker("new message");// 第一次提示消失的时候显示在通知栏上的
        builder1.setOngoing(true);
        builder1.setNumber(20);
        Notification build = builder1.build();
        manger.notify(LoongsConfig.MessageNotification.dialogueNotificationId, build);//id为1
    }
}
